<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      border-collapse: collapse;
    }

    th,
    td {
      border: 1px solid #ccc;
      padding: 10px;
      text-align: center;
    }

    tbody tr:nth-child(odd) {
      background-color: #eee;
    }
  </style>
</head>

<body>
  <p>
    <input id="keyword" type="search" placeholder="请输入水果名称">
    <input id="price1" style="width: 80px;" type="number" placeholder="起始价格">~
    <input id="price2" style="width: 80px;" type="number" placeholder="结束价格">
    <button onclick="search()">搜索</button>
  </p>
  <table width="500">
    <thead>
      <tr>
        <th>序号</th>
        <th>名称</th>
        <th>单价</th>
        <th>日期</th>
      </tr>
    </thead>
    <tbody id="list">

    </tbody>
  </table>
  <script>
    var fruit = [
      { id: 1, name: '苹果', price: 5, addtime: '2021-08-30' },
      { id: 1, name: '红富士苹果', price: 10, addtime: '2021-08-30' },
      { id: 2, name: '桔子', price: 2, addtime: '2021-08-27' },
      { id: 3, name: '香蕉', price: 3, addtime: '2021-08-26' },
      { id: 4, name: '菠萝', price: 6, addtime: '2021-08-29' },
      { id: 5, name: '葡萄', price: 12, addtime: '2021-08-24' },
      { id: 5, name: '西瓜', price: 2.5, addtime: '2021-08-23' },
    ];
    view();//先调用一次,让数据显示在页面上
    function search() {
      var condition = {
        keyword: keyword.value.trim(),
        price1: price1.value.trim(),
        price2: price2.value.trim(),
      }
      view(condition);
    }
    function view(condition = {}) {
      var temp = '';
      var keyword = condition.keyword;
      var price1 = condition.price1;
      var price2 = condition.price2;
      //匹配字符串
      var searchData = fruit.filter(function (item) {
        //判断keyword有没有值，有的话就模糊搜索，没有就给他一个true，强制为真，让他往后执行（可以做到前面不填，只用价格也可以搜索），后面也是一样
        return (keyword ? item.name.includes(keyword) : true) &&
          ((price1 ? item.price >= price1 : true) && (price2 ? item.price <= price2 : true));
      })
      // 如果没有匹配到，返回所有
      if (!searchData.length) {
        temp += `<tr align="center"><td colspan = "4">抱歉！暂无数据！</td></tr>`
      }
      // 循环输出匹配到的数据
      searchData.forEach(function (item, index) {
        temp += `<tr>
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${'￥' + item.price.toFixed(2)}</td>
            <td>${item.addtime}</td>
          </tr>`;
      })
      list.innerHTML = temp;
    }

  </script>

</body>

</html>